package com.zfl.thread.day04;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class CompletableDemo09 {

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Accessors(chain = true)
    private static class NetMall {
        private String mallName;

        public double price(String productName) {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
        }

        public static List<String> calculate(List<NetMall> netMalls, String productName) {
            return netMalls.stream()
                    .map(netMall -> String.format("<%s>价格在%s的价格是%.2f", productName
                            , netMall.getMallName(), netMall.price(productName)))
                    .collect(Collectors.toList());
        }

        public static List<String> calculateByCompletableFuture(List<NetMall> netMalls, String productName) {
            return netMalls.stream()
                    .map(netMall -> CompletableFuture.supplyAsync(()->{
                        return String.format("%s在%s上的价格是%.2f",productName,netMall,netMall.price(productName));
                    })).toList()
                    .stream()
                    .map(CompletableFuture::join)
                    .toList();
        }

    }

    public static void main(String[] args) {
        List<NetMall> list = Arrays.asList(new NetMall("JD"), new NetMall("TAOBAO"),
                new NetMall("PDD"), new NetMall("DANGDANG"));
        long start = System.currentTimeMillis();
        NetMall.calculate(list, "钢铁是怎样炼成的").forEach(System.out::println);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        start = System.currentTimeMillis();
        NetMall.calculateByCompletableFuture(list, "人月神话").forEach(System.out::println);
        end = System.currentTimeMillis();
        System.out.println(end - start);

    }

}
